<?php

namespace App\Console\Commands;

use App\Events\LoanRequestApplyEvent;
use App\Facades\SamLogFacade;
use App\Models\UserApplyRiskLog;
use App\Models\UserCertOcr;
use App\Models\UserLoanRequest;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckLoanRequestToApplyCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:loan_request_to_apply';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'find need to apply loan request';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $loan_list = UserLoanRequest::leftjoin('users','user_loan_requests.user_id','=','users.id')
            ->where('user_loan_requests.risk_status',UserApplyRiskLog::STATUS_SUCCESS)
            ->whereNotNull('users.nfsp_user_id')
            ->where('user_loan_requests.status',UserLoanRequest::STATUS_WAIT_FOR_RISK)
            ->select(['user_loan_requests.*','users.nfsp_user_id'])
            ->get();
        if($loan_list->count()>0){
            SamLogFacade::debug("查询到风控通过未申请授信的数据{$loan_list->count()}");
            foreach ($loan_list  as $index => $loan){
                $uploaded = UserCertOcr::where(['is_valid'=>1,'user_id'=>$loan->user_id])->get();
                $sign = 0;
                foreach ($uploaded as $k =>$v){
                    if(!empty($v->upload)){
                        $sign = 1;
                        break;
                    }
                }
                if(empty($sign)){
                    SamLogFacade::debug("本次申请授信列表第{$index}个：【{$loan->id}】的用户【{$loan->user_id}】未上传身份证");
                    continue;
                }else{
                    event(new LoanRequestApplyEvent($loan));
                    SamLogFacade::debug("本次申请授信列表第{$index}个：{$loan->id}推入队列");
                    SamLogFacade::debug("具体数据：".json_encode($loan,JSON_UNESCAPED_UNICODE));
                }
            }
        }
    }
}
